from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view

from goods.models import Goods
from api.serializers import GoodsSerializer


@api_view(['GET', 'POST'])
def get_list(request):
    if request.method == 'GET':
        goods = Goods.objects.all()
        serializers = GoodsSerializer(goods, many=True)
        return Response(serializers.data)
    elif request.method == 'POST':
        serializers = GoodsSerializer(data=request.data)
        if serializers.is_valid():
            serializers.save()
            return Response(serializers.data,status=status.HTTP_201_CREATED)


@api_view(['GET', 'PUT', 'DELETE'])
def get_detail(request,id):
    try:
        goods = Goods.objects.get(id=id)
    except Goods.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        serializers = GoodsSerializer(goods)
        return Response(serializers.data)
    elif request.method == 'PUT':
        serializers = GoodsSerializer(goods, data=request.data)
        if serializers.is_valid():
            serializers.save()
            return Response(serializers.data)
        return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        goods.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)